<?php

$relation = file_get_contents('./Result_7.json');
$relation = json_decode($relation, true);

$stepMap = array_column($relation, null, 'id');

$stepParentMap = $stepChildrenMap = $stepMap;
foreach ($relation as $relationItem) {
    if (array_key_exists($relationItem['parent_id'], $stepParentMap)) {
        $stepChildrenMap[$relationItem['parent_id']]['children'][] = &$stepChildrenMap[$relationItem['id']];
        $stepParentMap[$relationItem['id']]['parent'][] = &$stepParentMap[$relationItem['parent_id']];
    }
}


function getParent($map, $idList, &$res, $level = 0, $maxLevel = 0)
{
    if ($maxLevel > 0 && $level === $maxLevel) {
        return;
    }
    echo sprintf("<hr />%d", $level);
    if (empty($idList)) {
        return;
    }
    $nextLevel = [];
    foreach ($idList as $id) {
        if (empty($map[$id])) {
            continue;
        }
        if (empty($map[$id]['parent'])) {
            continue;
        }
        foreach ($map[$id]['parent'] as $parent) {
            if (empty($res[$parent['id']])) {
                echo sprintf('%s #### ',$parent['name']);
                $res[$parent['id']] = $parent;
                $nextLevel[$parent['id']] = $parent['id'];
            }
        }
    }
    if (!empty($nextLevel)) {
        getParent($map, $nextLevel, $res, ++$level, $maxLevel);
    }

}

getParent($stepParentMap, [64], $res, 0, 4);


foreach ($res as $i) {
    echo sprintf('%s <hr />', $i['name']);
}